import ora from 'ora';
import type { SpinnerOptions } from '../types/index.js';

export class SpinnerManager {
  private spinner: any;

  constructor() {
    this.spinner = null;
  }

  start(options: SpinnerOptions): void {
    if (this.spinner) {
      this.spinner.stop();
    }

    this.spinner = ora({
      text: options.text,
      color: options.color || 'cyan',
      spinner: (options.spinner as any) || 'dots',
    }).start();
  }

  update(text: string): void {
    if (this.spinner) {
      this.spinner.text = text;
    }
  }

  succeed(text?: string): void {
    if (this.spinner) {
      this.spinner.succeed(text);
      this.spinner = null;
    }
  }

  fail(text?: string): void {
    if (this.spinner) {
      this.spinner.fail(text);
      this.spinner = null;
    }
  }

  warn(text?: string): void {
    if (this.spinner) {
      this.spinner.warn(text);
      this.spinner = null;
    }
  }

  info(text?: string): void {
    if (this.spinner) {
      this.spinner.info(text);
      this.spinner = null;
    }
  }

  stop(): void {
    if (this.spinner) {
      this.spinner.stop();
      this.spinner = null;
    }
  }

  isSpinning(): boolean {
    return this.spinner !== null;
  }
}

export const createSpinner = (): SpinnerManager => {
  return new SpinnerManager();
};
